package org.wisteria.socket.netty4.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wisteria.socket.SocketClient;

import java.util.concurrent.TimeUnit;

public class Netty4SocketClient implements SocketClient {
    private static final Logger logger = LoggerFactory.getLogger(Netty4SocketClient.class);

    private String ip;
    private int port;

    private NioEventLoopGroup workerGroup;
    private Channel channel;

    public Netty4SocketClient() {}

    public Netty4SocketClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
        connect();
    }

    public void send(String message) {
        if (channel != null && channel.isOpen()) {
            channel.writeAndFlush(message);
        } else {
            logger.error("Channel is null | closed");
        }
    }

    private void connect() {
        workerGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap
                .group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    public void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8))
                        .addLast(new LineBasedFrameDecoder(Integer.MAX_VALUE))
                        .addLast(new ClientChannelHandler())
                        .addLast(new StringDecoder());
                    }
                });
        try {
            ChannelFuture future = bootstrap.connect(ip, port).sync();
            //boolean result = future.awaitUninterruptibly(3000, TimeUnit.MILLISECONDS);
            if (future.isSuccess()) {
                channel = future.channel();
                logger.debug("Netty Server Connect Success. IP:{},PORT:{}", ip, port);
            } else {
                disConnect();
                logger.error("Netty Server Connect Fail. IP:{},PORT:{}", ip, port);
            }
        } catch (Exception e) {
            logger.error("连接异常。IP: " + ip + ":" + port + "." + e.getMessage());
            disConnect();
        }
    }

    /**
     * 断开tcp连接.
     */
    private void disConnect() {
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
            workerGroup = null;
        }

        if (channel != null) {
            channel.close();
            channel = null;
        }
    }
}
